﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Puddy.Utils;

using FacebookUtils;
using Tools;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using Puddy.UserControls;
using Microsoft.Phone.Tasks;
using System.Windows.Navigation;
using TwitterApp;
using Hammock;
using Hammock.Web;
using Hammock.Authentication.OAuth;


namespace Puddy
{
    public partial class SettingPage : PhoneApplicationPage
    {
        bool navigateToFacebook = false;

        public SettingPage()
        {
            InitializeComponent();

            init();
        }

        bool loadFinished = false;

        void init()
        {
            if (App.Setting.DistanceType == Constants.KM_TYPE)
            {
                radioBtn_km.IsChecked = true;
                radioBtn_miles.IsChecked = false;

                tbl_distanceType.Text = "KM";
            }
            else
            {
                radioBtn_km.IsChecked = false;
                radioBtn_miles.IsChecked = true;

                tbl_distanceType.Text = "Miles";
            }

            List<String> listKm = new List<string> { "0.5", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
            listPicker_distance.ItemsSource = listKm;

            listPicker_distance.SelectedItem = modifyKmString(App.Setting.Distance);

            loadFinished = true;
        }

        String modifyKmString(float distance)
        {
            if (distance < 1)
            {
                return distance.ToString("f1");
            }
            else
            {
                return distance.ToString("f0");
            }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (App.RunningAlarm)
            {
                this.NavigationService.Navigate(new Uri("/AlarmPage.xaml", UriKind.Relative));
            }

            if (App.ShouldShowMessTurnOffLocation)
            {
                App.ShouldShowMessTurnOffLocation = false;
                MessageBox.Show(Constants.MES_TURN_OFF_LOCATION);

            }

            if (navigateToFacebook)
            {
                if (FacebookClient.Instance.AccessToken != null || FacebookClient.Instance.AccessToken != "")
                {
                    this.NavigationService.Navigate(new Uri("/UserControls/FacebookPage.xaml", UriKind.Relative));
                }
            }

        }

        protected async override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            await RestoreData.CreateJsonSetting(App.Setting);
        }


        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.GoBack();
        }

        private void btnLike_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
        }

        private  void btnFaceBook_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if ("".Equals(FacebookClient.Instance.AccessToken))
            {
                this.NavigationService.Navigate(new Uri("/UserControls/FacebookPage.xaml", UriKind.Relative));
            }
            else
            {
                this.NavigationService.Navigate(new Uri("/UserControls/FacebookPage.xaml", UriKind.Relative));
            }

             

        }

        void PostMessageOnWallCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            if (e.Cancelled)
                return;
            if (e.Error != null)
            {
                MessageBox.Show("Error Occurred: " + e.Error.Message);
                return;
            }

            System.Diagnostics.Debug.WriteLine(e.Result);

            string result = e.Result;
            byte[] data = Encoding.UTF8.GetBytes(result);
            MemoryStream memStream = new MemoryStream(data);
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ResponseData));
            ResponseData responseData = (ResponseData)serializer.ReadObject(memStream);

            if (responseData.id != null && !responseData.id.Equals(""))
            {
                // Success
                MessageBox.Show(Constants.TEXT_POST_OK);
            }
            else if (responseData.error != null && responseData.error.code == 190)
            {
                if (responseData.error.error_subcode == 463)
                {
                    // Access Token Expired, need to get new token
                    FacebookClient.Instance.ExchangeAccessToken(new UploadStringCompletedEventHandler(ExchangeAccessTokenCompleted));
                }
                else
                {
                    // Another Error with Access Token, need to clear the Access Token
                    FacebookClient.Instance.AccessToken = "";
                    //SetLoggedInState(false);
                }
            }
            else
            {
                // Error
            }
        }

        void ExchangeAccessTokenCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            // Acquire access_token and expires timestamp
            IEnumerable<KeyValuePair<string, string>> pairs = UriToolKits.ParseQueryString(e.Result);
            string accessToken = KeyValuePairUtils.GetValue(pairs, "access_token");

            if (accessToken != null && !accessToken.Equals(""))
            {
                MessageBox.Show("Access Token Exchange Failed");
                return;
            }

            // Save access_token
            FacebookClient.Instance.AccessToken = accessToken;
            FacebookClient.Instance.PostMessageOnWall(Constants.TEXT_TO_POST, new UploadStringCompletedEventHandler(PostMessageOnWallCompleted));
        }

        

        private void btnTwitter_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            String accessToken_twitter = HelperMethods.GetKeyValue<string>("AccessToken");
            String accessTokenSecret_twitter = HelperMethods.GetKeyValue<string>("AccessTokenSecret");
            String userScreenName_twitter = HelperMethods.GetKeyValue<string>("ScreenName");

            if (string.IsNullOrEmpty(accessToken_twitter) || string.IsNullOrEmpty(accessTokenSecret_twitter))
            {
                var requestTokenQuery = oAuthHelper.GetRequestTokenQuery();
                requestTokenQuery.RequestAsync(TwitterSettings.RequestTokenUri, null);
                requestTokenQuery.QueryResponse += new EventHandler<WebQueryResponseEventArgs>(requestTokenQuery_QueryResponse);
            }
            else
            {

                postTweetter();
            }
        }

        private void postTweetter()
        {
            String accessToken = HelperMethods.GetKeyValue<string>("AccessToken");
            String accessTokenSecret = HelperMethods.GetKeyValue<string>("AccessTokenSecret");

            var credentials = new OAuthCredentials
            {
                Type = OAuthType.ProtectedResource,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
                ConsumerKey = TwitterSettings.consumerKey,
                ConsumerSecret = TwitterSettings.consumerKeySecret,
                Token = accessToken,
                TokenSecret = accessTokenSecret,
                Version = "1.0"
            };

            var restClient = new RestClient
            {
                Authority = TwitterSettings.StatusUpdateUrl,
                HasElevatedPermissions = true,
                Credentials = credentials,
                Method = WebMethod.Post
            };

            restClient.AddHeader("Content-Type", "application/x-www-form-urlencoded");

            // Create a Rest Request and fire it
            var restRequest = new RestRequest
            {
                Path = "1/statuses/update.xml?status=" + Constants.TEXT_TO_POST + " on " + DateTime.Now.ToString()
            };

            var ByteData = Encoding.UTF8.GetBytes(Constants.TEXT_TO_POST + " on " + DateTime.Now.ToString());
            restRequest.AddPostContent(ByteData);
            restClient.BeginRequest(restRequest, new RestCallback(PostTweetRequestCallback));
        }

        private void PostTweetRequestCallback(RestRequest request, Hammock.RestResponse response, object obj)
        {
            Dispatcher.BeginInvoke(() =>
            {
                MessageBox.Show(Constants.TEXT_POST_OK);
            });
            
        }

        void requestTokenQuery_QueryResponse(object sender, WebQueryResponseEventArgs e)
        {
            try
            {
                var parameters = HelperMethods.GetQueryParameters(e.Response);
                String OAuthTokenKey_twitter = parameters["oauth_token"];
                String tokenSecret_twitter = parameters["oauth_token_secret"];
                var authorizeUrl = TwitterSettings.AuthorizeUri + "?oauth_token=" + OAuthTokenKey_twitter;

                Dispatcher.BeginInvoke(() =>
                {
                    //this.objAuthorizeBrowserControl.Navigate(new Uri(authorizeUrl));
                    NavigationService.Navigate(new Uri("/UserControls/TwitterLoginPage.xaml?oauth_token=" +OAuthTokenKey_twitter+ "&oauth_token_secret=" + tokenSecret_twitter, UriKind.Relative));
                });
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show(ex.Message);
                });
            }

        }

        

        


        private void btnGooglePlus_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/UserControls/GooglePlusLoginPage.xaml", UriKind.RelativeOrAbsolute));
        }

        private void HyperlinkButton_Click_1(object sender, System.Windows.RoutedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
        }

        private void Logo_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            WebBrowserTask webBrowserTask = new WebBrowserTask();
            webBrowserTask.Uri = new Uri("http://www.covexis.com");
            webBrowserTask.Show();
        }

        private void btn_sendEmail_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            EmailComposeTask emailComposeTask = new EmailComposeTask();
            emailComposeTask.To = "enquiry@covexis.com";
            emailComposeTask.Show();
        }

        private void radioBtn_km_Checked(object sender, System.Windows.RoutedEventArgs e)
        {
            App.Setting.DistanceType = Constants.KM_TYPE;
            tbl_distanceType.Text = "KM";


        }

        private void radioBtn_miles_Checked(object sender, System.Windows.RoutedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
            App.Setting.DistanceType = Constants.MILES_TYPE;
            tbl_distanceType.Text = "Miles";


  
        }

        //private void tb_distance_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        //{
        //    // TODO: Add event handler implementation here.
        //}
		
        //bool isFocus = false;

        //private void tb_distance_GotFocus(object sender, System.Windows.RoutedEventArgs e)
        //{
        //    // TODO: Add event handler implementation here.
        //    isFocus = true;
        //}

        //private void tb_distance_LostFocus(object sender, System.Windows.RoutedEventArgs e)
        //{
        //    // TODO: Add event handler implementation here.
        //    if (isFocus)
        //    {
        //        if (tb_distance.Text != "")
        //        {
        //            try
        //            {
        //                float distance;
        //                bool rs = float.TryParse(tb_distance.Text, out distance);
        //                if (rs)
        //                {
        //                    App.Setting.Distance = distance;
        //                }
        //                else
        //                {
        //                    tb_distance.Text = App.Setting.Distance.ToString();
        //                }
        //            }
        //            catch (System.Exception ex)
        //            {
        //                tb_distance.Text = App.Setting.Distance.ToString();
        //            }
        //        }
        //        else
        //        {
        //            tb_distance.Text = App.Setting.Distance.ToString();
        //        }
        //    }
        //}

        private void btn_sendEmail_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
        	// TODO: Add event handler implementation here.	
        }

        private void btn_sendEmail_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
        	// TODO: Add event handler implementation here.
			
        }

        private void listPicker_distance_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (loadFinished)
            {
                float preDistance = App.Setting.Distance;
                if (listPicker_distance.SelectedItem != null)
                    App.Setting.Distance = float.Parse(listPicker_distance.SelectedItem as String);

                //if change distance alarm and and new distance > old distance -> recheck alarm
                if (App.Setting.Distance > preDistance)
                {
                    App.recheckLocation();
                }
            }
        }

        
    }
}